import * as THREE from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import { carBody, carSphere,carBody2 } from './carMaterial'

class car3D{
  scene: THREE.Scene | null
  moduleName: string
  constructor(scene: THREE.Scene | null, moduleName: string){
    this.scene = scene
    this.moduleName = moduleName
    this.initFooterMesh()
    this.initMesh()
  }

  initFooterMesh(){
    const footer = new THREE.Mesh(
      new THREE.PlaneGeometry(10,10),
      new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.8, side: THREE.DoubleSide})
    )
    footer.rotation.x = -Math.PI / 2
    footer.position.set(0,0,-1)
    this.scene!.add(footer)
  }
  addGLTFModel(modelName:string){
    return new Promise((resolve, reject)=>{
      try{
        const loader = new GLTFLoader().setPath('3dModules/car/')
        loader.load(modelName,(gltf)=>{
          const motorModel = gltf.scene
          motorModel.traverse((obj:any)=>{
            this.materialShow(obj)
            this.materialCar(obj)
            obj.castShadow = true 
          })
          this.scene!.add(motorModel)
          resolve(modelName+'加载成功')        
        })
      } catch(e){
        reject(modelName+'加载失败'+e)
      }
    })
  }

  initMesh(){
    this.addGLTFModel(this.moduleName).then(res=>{
      console.log(res);
    }).catch(err=>{
      console.log(err);
    })
  }

  /**
   * Object_31 地板
   * Object_13 车阴影
   * @param child 
   */
  materialShow(child: any){
    const childName = ["Object_31","Object_13"]  //模型树需要隐藏的材质名称
    if(childName.includes(child.name)){     
      child.material.visible = false
    }
  }

  materialCar(child: any){
    switch(child.name){
      case "Object_8":
        child.material = carBody2
        break
      case "Object_10":
        child.material = carBody
        break
      case "Object_57":
        child.material = carSphere      
        break
      case "Object_58":
        child.material = carSphere      
        break
      case "Object_59":
        child.material = carSphere      
        break
    }
  }
}

export default car3D